package com.wsx.rpc.metrics.controller;

import com.codahale.metrics.Counter;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Timer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * @author wangshuaixin
 * @Title: com.wsx.rpc.metrics.controller.MetricsController
 * @Description: TODO
 * @date 2018/11/29
 */
@RestController
@RequestMapping("/metrics")
public class MetricsController {


    @Autowired
    private Meter meter;

    @RequestMapping(
            value = "/meter",
            method = {RequestMethod.GET}
    )
    public String meter() {
        meter.mark();
        return "hello meter";
    }


    @Autowired
    private Histogram histogram;

    @RequestMapping(
            value = "/histogram",
            method = {RequestMethod.GET}
    )
    public String histogram() {
        histogram.update(new Random().nextInt(10));
        return "hello histogram";
    }


    @Autowired
    private Counter counter;

    @RequestMapping(
            value = "/counter",
            method = {RequestMethod.GET}
    )
    public String counter() {
        counter.inc();
        //释放时调用下面
        //counter.dec();
        return "hello counter";
    }

    @Autowired
    private Timer timer;

    @RequestMapping(
            value = "/timer",
            method = {RequestMethod.GET}
    )
    public String timer() {
        final Timer.Context context = timer.time();
        try {
            Thread.sleep(new Random().nextInt(100));
            return "hello timer";
        } catch (Exception e) {
            return "hello timer e";
        } finally {
            context.stop();
        }
    }
}
